package net.alan.modules.service.impl;

import net.alan.common.constants.ENoticeType;
import net.alan.common.constants.EProjectLogType;
import net.alan.common.utils.CompareUtil;
import net.alan.modules.bean.*;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.repository.*;
import net.alan.modules.service.INoticeService;
import net.alan.modules.service.IProjectService;
import net.alan.modules.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Service
public class ProjectServiceImpl extends BaseServiceImpl implements IProjectService {
    private static final Logger logger = LoggerFactory.getLogger(ProjectServiceImpl.class);
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private ProjectNoteHistoryRepository projectNoteHistoryRepository;
    @Autowired
    private ProjectNoteRepository projectNoteRepository;
    @Autowired
    private ProjectLogRepository projectLogRepository;
    @Autowired
    private ProjectAttachRepository projectAttachRepository;
    @Autowired
    private IUserService userService;
    @Autowired
    private INoticeService noticeService;

    @Override
    public JpaRepository getJpaRepository(Class<?> cla) {
        if (isSame(cla, Project.class)) {
            return projectRepository;
        } else if (isSame(cla, ProjectLog.class)) {
            return projectLogRepository;
        } else if (isSame(cla, ProjectNote.class)) {
            return projectNoteRepository;
        } else if (isSame(cla, ProjectNoteHistory.class)) {
            return projectNoteHistoryRepository;
        } else if (isSame(cla, ProjectAttach.class)) {
            return projectAttachRepository;
        }
        return null;
    }

    @Override
    public void joinProject(Integer userId, Integer projectId) {
        Project project = projectRepository.getOne(projectId);
        if (project != null) {
            UserProject userProject = new UserProject();
            userProject.setProjectId(project.getId());
            userProject.setUser(userService.getById(User.class, userId));
            //保存组员
            this.userService.addUserProject(userProject);
        }
    }

    @Override
    public Result moveProject(Integer id, Integer userId) {
        Project project = getById(Project.class, id);
        Integer uId = WebContextUtil.getUserId();
        if (project.getUser().getId() != uId) {
            return ResultUtil.noRole();
        } else if (userId == uId) {
            return ResultUtil.error("项目不能移交给自己");
        } else if (userId == null || userId == 0) {
            return ResultUtil.error("必须填写项目接收者");
        }
        User user = userService.getById(User.class, userId);
        project.setUser(user);
        this.projectRepository.save(project);
        this.addProjectLog(id, null, EProjectLogType.common, "项目移交给-" + user.getName());
        return ResultUtil.success();
    }

    @Override
    public Result editProject(Project tmp) {
        Project project = getById(Project.class, tmp.getId());
        if (project.getUser().getId() != WebContextUtil.getUserId()) {
            return ResultUtil.noRole();
        }
        project.setName(tmp.getName());
        project.setJoinTYpe(tmp.getJoinTYpe());
        this.projectRepository.save(project);
        WebContextUtil.projectMap.put(project.getId(), project.getName());
        return ResultUtil.success();
    }

    @Override
    public Result addProject(Project project) {
        User user = WebContextUtil.getCurrentUser().getUser();
        int gnum = this.projectRepository.countByUserIdAndDeletedTrue(user.getId());
        if (gnum > user.getMaxProject()) {
            return ResultUtil.error("已达到最大项目数量，请联系客服人员进行扩充！");
        }

        //保存项目
        this.projectRepository.save(project);
        addProjectLog(project.getId(), EProjectLogType.projectAdd, "创建项目-" + project.getName());
        UserProject userProject = new UserProject();
        userProject.setProjectId(project.getId());
        userProject.setUser(WebContextUtil.getCurrentUser().getUser());
        //保存组员
        this.userService.addUserProject(userProject);

        WebContextUtil.projectMap.put(project.getId(), project.getName());
        //生成日志
        return ResultUtil.success();
    }


    @Override
    public void addProjectLog(Integer projectId, Integer taskId, EProjectLogType projectLogType, String detail) {
        ProjectLog projectLog = new ProjectLog();
        projectLog.setProjectId(projectId);
        projectLog.setTaskId(taskId);
        projectLog.setUser(WebContextUtil.getCurrentUser().getUser());
        projectLog.setProjectlogType(projectLogType.name());
        projectLog.setDetail(detail);
        this.projectLogRepository.save(projectLog);
    }

    public void addProjectLog(Integer projectId, EProjectLogType projectLogTypeLogType, String detail) {
        this.addProjectLog(projectId, -1, projectLogTypeLogType, detail);
    }


    @Override
    public List<Project> findProjectByUserId(Integer userId) {
        return this.projectRepository.findByUserId(userId);
    }

    @Override
    public Page<ProjectNote> findProjectNoteByProjectId(Integer projectId, PageModel pageModel) {
        return this.projectNoteRepository.findByProjectId(projectId, pageModel.getPageable());
    }

    @Override
    public Page<ProjectAttach> findProjectAttachByProjectId(Integer projectId, PageModel pageModel) {
        return this.projectAttachRepository.findByProjectId(projectId, pageModel.getPageable());
    }

    @Override
    public Page<ProjectAttach> findProjectAttachByTaskId(Integer taskId, PageModel pageModel) {
        return this.projectAttachRepository.findByTaskId(taskId, pageModel.getPageable());
    }

    @Override
    public Page<ProjectNoteHistory> findProjectNoteHistoryByNoteId(Integer noteId, PageModel pageModel) {
        return this.projectNoteHistoryRepository.findByNoteId(noteId, pageModel.getPageable());
    }

    @Override
    public Page<ProjectLog> findProjectLogByProjectId(Integer projectId, PageModel pageModel) {
        return this.projectLogRepository.findByProjectId(projectId, pageModel.getPageable());
    }

    @Override
    public Page<ProjectLog> findProjectLogByTaskId(Integer taskId, PageModel pageModel) {
        return this.projectLogRepository.findByTaskId(taskId, pageModel.getPageable());
    }

    @Override
    public Result deleteProjectAttach(Integer id) {
        ProjectAttach attach = getById(ProjectAttach.class, id);
        if (attach.getUserId() != WebContextUtil.getUserId()) {
            return ResultUtil.noRole();
        }
        if (attach.getUserId() == WebContextUtil.getUserId()) {
            this.projectAttachRepository.delete(id);
            this.addProjectLog(attach.getProjectId(), EProjectLogType.common, "删除资料-" + attach.getFileName());
        }
        return ResultUtil.success();
    }

    @Override
    public Result deleteProjectNote(Integer id) {
        ProjectNote note = getById(ProjectNote.class, id);
        if (note.getUserId() != WebContextUtil.getUserId()) {
            return ResultUtil.noRole();
        } else if (note.getVersion() == 1 && note.getUserId() == WebContextUtil.getUserId()) {
            this.projectNoteRepository.delete(id);
            this.addProjectLog(note.getProjectId(), EProjectLogType.common, "删除笔记-" + note.getName());
        }
        return ResultUtil.error("该笔记已被编辑多次，不能进行删除");
    }

    @Override
    public Result deleteProject(Integer id) {
        Result result = ResultUtil.success();
        try {
            //标记为删除
            Project project = getById(Project.class, id);
            if (project.getUser().getId() != WebContextUtil.getUserId()) {
                return ResultUtil.noRole();
            }
            project.setDeleted(true);
            this.projectRepository.save(project);
            List<UserProject> list = this.userService.findUserProjectByProjectId(id);
            if (list != null) {
                for (UserProject ug : list) {
                    noticeService.addNotice(project.getName() + "-已被解散", ENoticeType.projectDelete, id, ug.getId());
                }
            }
        } catch (Exception e) {
            result = ResultUtil.error("删除异常");
        }
        return result;
    }

    @Override
    public Result saveNote(String content, ProjectNote note) {
        try {
            note.setContent(CompareUtil.wrapHtml(note.getContent()));
            Integer noteId = note.getId();
            if (noteId != null && noteId > 0) {
                ProjectNoteHistory noteHistory = new ProjectNoteHistory();
                noteHistory.setUserId(note.getUserId());
                noteHistory.setContent(content);
                noteHistory.setName(note.getName());
                noteHistory.setNoteId(noteId);
                noteHistory.setCreated(note.getModified());
                noteHistory.setVersion(note.getVersion());
                noteHistory.setLastUserId(note.getLastUserId());
                this.projectNoteHistoryRepository.save(noteHistory);
            }
            note.setLastUserId(WebContextUtil.getUserId());
            note.setModified(new Date());
            note.setVersion(note.getVersion() + 1);
            this.projectNoteRepository.save(note);
            this.addProjectLog(note.getProjectId(), EProjectLogType.common, "编辑笔记-" + note.getName());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("错误");
        }
        return ResultUtil.success();
    }
}
